/**
 * Project Name:danbay
 * File Name:RSAUtil.java
 * Package Name:cc.messcat.util
 * Date:2017年11月12日下午10:51:21
 * Copyright © 2016 －2017 www.danbay.cn All Rights
 */

package com.danbay.framework.utils.security;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;

import javax.crypto.Cipher;

/**
 * Description:《RSA加密解密工具》 <br/>
 * Date: 2017年11月12日 下午10:51:21 <br/>
 * 
 * @author Zhouych
 * @version 1.0
 * @since JDK 1.8
 */
public class RSAUtil {

	/**
	 * RSA加密算法
	 */
	private static final String ALGORITHM = "RSA";

	private static final String PUBLIC_KEY = "publicKey";

	private static final String PRIVATE_KEY = "privateKey";

	private static final int KEY_SIZE = 1024;

	/**
	 * getKeys:《生成密钥对》. <br/>
	 *
	 * @author Zhouych
	 * @return
	 */
	public static HashMap<String, Object> getKeys() {
		try {
			KeyPairGenerator keyPairGen;
			keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
			keyPairGen.initialize(KEY_SIZE);
			KeyPair keyPair = keyPairGen.generateKeyPair();
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
			HashMap<String, Object> keyMap = new HashMap<String, Object>();
			keyMap.put(PUBLIC_KEY, publicKey);
			keyMap.put(PRIVATE_KEY, privateKey);
			return keyMap;
		} catch (NoSuchAlgorithmException e) {
		}
		return null;
	}

	/**
	 * getPublicKey:《构建公钥》. <br/>
	 *
	 * @author Zhouych
	 * @param encoded
	 * @return
	 */
	public static RSAPublicKey getPublicKey(byte[] encoded) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * getPrivateKey:《构建私钥》. <br/>
	 *
	 * @author Zhouych
	 * @param encoded
	 * @return
	 */
	public static RSAPrivateKey getPrivateKey(byte[] encoded) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * encryptByPublicKey:《公钥加密》. <br/>
	 *
	 * @author Zhouych
	 * @param data
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		// 模长
		int keyLength = publicKey.getModulus().bitLength() / 8;
		// 加密数据长度 <= 模长-11
		String[] datas = splitString(data, keyLength - 11);
		StringBuffer encrypt = new StringBuffer();
		// 如果明文长度大于模长-11则要分组加密
		for (String d : datas) {
			encrypt.append(bcdToStr(cipher.doFinal(d.getBytes())));
		}
		return encrypt.toString();
	}
	
	/**
	 * decryptByPrivateKey:《私钥解密》. <br/>
	 *
	 * @author Zhouych
	 * @param data
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        //模长
        int key_len = privateKey.getModulus().bitLength() / 8;
        byte[] bytes = data.getBytes();
        byte[] bcd = asciiTobcd(bytes, bytes.length);
        //如果密文长度大于模长则要分组解密
        StringBuffer decrypt = new StringBuffer();
        byte[][] arrays = splitArray(bcd, key_len);
        for(byte[] arr : arrays){
        	decrypt.append(new String(cipher.doFinal(arr)));
        }
        return decrypt.toString();
    }
	
	
	/**
	 * encryptByPrivateKey:《私钥加密》. <br/>
	 *
	 * @author Zhouych
	 * @param data
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String encryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		// 模长
		int keyLength = privateKey.getModulus().bitLength() / 8;
		// 加密数据长度 <= 模长-11
		String[] datas = splitString(data, keyLength - 11);
		StringBuffer encrypt = new StringBuffer();
		// 如果明文长度大于模长-11则要分组加密
		for (String d : datas) {
			encrypt.append(bcdToStr(cipher.doFinal(d.getBytes())));
		}
		return encrypt.toString();
	}
	
	/**
	 * decryptByPublicKey:《公钥解密》. <br/>
	 *
	 * @author Zhouych
	 * @param data
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPublicKey(String data, RSAPublicKey publicKey)
            throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        //模长
        int key_len = publicKey.getModulus().bitLength() / 8;
        byte[] bytes = data.getBytes();
        byte[] bcd = asciiTobcd(bytes, bytes.length);
        //如果密文长度大于模长则要分组解密
        StringBuffer decrypt = new StringBuffer();
        byte[][] arrays = splitArray(bcd, key_len);
        for(byte[] arr : arrays){
        	decrypt.append(new String(cipher.doFinal(arr)));
        }
        return decrypt.toString();
    }
	

	/**
	 * ASCII码转BCD码
	 */
	public static byte[] asciiTobcd(byte[] ascii, int ascLength) {
		byte[] bcd = new byte[ascLength / 2];
		int j = 0;
		for (int i = 0; i < (ascLength + 1) / 2; i++) {
			bcd[i] = asciiTobcd(ascii[j++]);
			bcd[i] = (byte) (((j >= ascLength) ? 0x00 : asciiTobcd(ascii[j++])) + (bcd[i] << 4));
		}
		return bcd;
	}

	private static byte asciiTobcd(byte asc) {
		byte bcd;
		if ((asc >= '0') && (asc <= '9'))
			bcd = (byte) (asc - '0');
		else if ((asc >= 'A') && (asc <= 'F'))
			bcd = (byte) (asc - 'A' + 10);
		else if ((asc >= 'a') && (asc <= 'f'))
			bcd = (byte) (asc - 'a' + 10);
		else
			bcd = (byte) (asc - 48);
		return bcd;
	}

	/**
	 * BCD转字符串
	 */
	public static String bcdToStr(byte[] bytes) {
		char temp[] = new char[bytes.length * 2], val;

		for (int i = 0; i < bytes.length; i++) {
			val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
			temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
			val = (char) (bytes[i] & 0x0f);
			temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
		}
		return new String(temp);
	}

	/**
	 * 拆分字符串
	 */
	public static String[] splitString(String string, int len) {
		int x = string.length() / len;
		int y = string.length() % len;
		int z = 0;
		if (y != 0) {
			z = 1;
		}
		String[] strings = new String[x + z];
		String str = "";
		for (int i = 0; i < x + z; i++) {
			if (i == x + z - 1 && y != 0) {
				str = string.substring(i * len, i * len + y);
			} else {
				str = string.substring(i * len, i * len + len);
			}
			strings[i] = str;
		}
		return strings;
	}

	/**
	 * 拆分数组
	 */
	public static byte[][] splitArray(byte[] data, int len) {
		int x = data.length / len;
		int y = data.length % len;
		int z = 0;
		if (y != 0) {
			z = 1;
		}
		byte[][] arrays = new byte[x + z][];
		byte[] arr;
		for (int i = 0; i < x + z; i++) {
			arr = new byte[len];
			if (i == x + z - 1 && y != 0) {
				System.arraycopy(data, i * len, arr, 0, y);
			} else {
				System.arraycopy(data, i * len, arr, 0, len);
			}
			arrays[i] = arr;
		}
		return arrays;
	}
}
